package com.syni.mdd.yhd.common.all.service.impl;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ParamsMap;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsBusinessCouponDao;
import com.syni.mdd.yhd.common.all.dto.requestDto.business.BusinessCouponReDto;
import com.syni.mdd.yhd.common.all.entity.BmsBusinessCoupon;
import com.syni.mdd.yhd.common.all.entity.BmsDxGroupBuy;
import com.syni.mdd.yhd.common.all.entity.BmsDxSubFood;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsUserReceCoupon;
import com.syni.mdd.yhd.common.all.quartz.QuartzDo;
import com.syni.mdd.yhd.common.all.quartz.businessCoupon.job.CouponAsOfJob;
import com.syni.mdd.yhd.common.all.quartz.businessCoupon.job.CouponToSendJob;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.yhd.common.all.utils.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @className
 * @description TOO
 * @Author hwq
 * @DATE 2019/9/23 10:34
 * @VERSION 1.0
 **/
@Service
public class BmsBusinessCouponServiceImpl extends BaseService<BmsBusinessCoupon, Integer> implements BmsBusinessCouponService {

    private final String AUTO_SEND_KEY = "job_coupon_send_id_";
    private final String AUTO_OFF_KEY = "job_coupon_off_id_";

    @Autowired
    BmsBusinessCouponDao bmsBusinessCouponDao;

    @Autowired
    BmsDxSubFoodService bmsDxSubFoodService;

    @Autowired
    BmsDxGroupBuyService bmsDxGroupBuyService;

    @Autowired
    BmsUserReceCouponService bmsUserReceCouponService;

    @Autowired
    BmsBusinessCouponService bmsBusinessCouponService;

    @Autowired
    BmsVerRecordService bmsVerRecordService;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public BmsBusinessCouponDao getBaseDao() {
        return bmsBusinessCouponDao;
    }

    @Override
    public Map<String, Object> createCoupon(BusinessCouponReDto businessCouponReDto) {
        Integer id = businessCouponReDto.getId();
        BmsBusinessCoupon bmsBusinessCoupon;
        Date sendStartTime = DateTimeUtils.converStringToDate(businessCouponReDto.getSendStartTime(),DateTimeUtils.DATE_PATTERN_TIMESTAMP_04);
        Date sendEndTime = DateTimeUtils.converStringToDate(businessCouponReDto.getSendEndTime(),DateTimeUtils.DATE_PATTERN_TIMESTAMP_04);
        Date startTime = DateTimeUtils.converStringToDate(businessCouponReDto.getStartTime(),DateTimeUtils.DATE_PATTERN_TIMESTAMP_04);
        Date endTime = DateTimeUtils.converStringToDate(businessCouponReDto.getEndTime(),DateTimeUtils.DATE_PATTERN_TIMESTAMP_04);
        if(id == null || id == Constants.COMMON_FLAG_FALSE_INT){
            //新建
            businessCouponReDto.setId(null);
            bmsBusinessCoupon = new BmsBusinessCoupon();
            bmsBusinessCoupon.setIsDelete(Constants.COMMON_FLAG_FALSE_INT);
            BeanUtils.copyProperties(businessCouponReDto,bmsBusinessCoupon);
            if(checkDisMax(sendStartTime,sendEndTime,businessCouponReDto.getBusinessId())){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_COUPON_IS_MAX,ResultMsg.CODE_BUSINESS_COUPON_IS_MAX);
            }
        }else {
            //编辑
            bmsBusinessCoupon = bmsBusinessCouponDao.findByIdAndIsDelete(id,Constants.COMMON_FLAG_FALSE_INT);
            if(bmsBusinessCoupon == null){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_COUPON_NO_EXIST,ResultMsg.CODE_BUSINESS_COUPON_NO_EXIST);
            }
            if(bmsBusinessCoupon.getStatus() == Constants.COUPON_STOP) {
                //新建券
                bmsBusinessCoupon = new BmsBusinessCoupon();
                BeanUtils.copyProperties(businessCouponReDto,bmsBusinessCoupon);
                bmsBusinessCoupon.setId(null);
                bmsBusinessCoupon.setIsDelete(Constants.COMMON_FLAG_FALSE_INT);
                if(checkDisMax(sendStartTime,sendEndTime,businessCouponReDto.getBusinessId())){
                    return ResultMapHelper.result(ResultCode.CODE_BUSINESS_COUPON_IS_MAX,ResultMsg.CODE_BUSINESS_COUPON_IS_MAX);
                }
            }
        }
        bmsBusinessCoupon.setSendStartTime(sendStartTime);
        bmsBusinessCoupon.setSendEndTime(sendEndTime);
        bmsBusinessCoupon.setStartTime(startTime);
        bmsBusinessCoupon.setEndTime(endTime);
        if(businessCouponReDto.getCouponType() == Constants.BUSINESS_COUPON_VOUCHERS){
            bmsBusinessCoupon.setCouponContent(bmsBusinessCoupon.getCouponContent());
            Map<String,Object> contentData = JSON.parseObject(bmsBusinessCoupon.getCouponContent());
            bmsBusinessCoupon.setCouponName(String.format("%s元无门槛代金券",contentData.get("amount")));
        }else if(businessCouponReDto.getCouponType() == Constants.BUSINESS_COUPON_FOOD){
            Map<String,Object> contentData = JSON.parseObject(bmsBusinessCoupon.getCouponContent());
            Integer subId = Integer.parseInt(contentData.get("subId").toString());
            //查询该菜品库
            BmsDxSubFood bmsDxSubFood = bmsDxSubFoodService.getSubFoodByIds(subId);
            if(bmsDxSubFood == null){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_FOOD_NO_EXIST,ResultMsg.CODE_BUSINESS_FOOD_NO_EXIST);
            }
            bmsBusinessCoupon.setCouponName(bmsDxSubFood.getFoodName());
            bmsBusinessCoupon.setCouponContent(JSON.toJSONString(bmsDxSubFood));
        }else if(businessCouponReDto.getCouponType() == Constants.BUSINESS_COUPON_GROUP_BUY){
            Map<String,Object> contentData = JSON.parseObject(bmsBusinessCoupon.getCouponContent());
            Integer groupBuyId = Integer.parseInt(contentData.get("groupBuyId").toString());
            //查询该团购
            BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyService.getGroupBuyById(groupBuyId);
            if(bmsDxGroupBuy == null){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST_GROUP_BUY,ResultMsg.CODE_BUSINESS_NO_EXIST_GROUP_BUY);
            }
            bmsBusinessCoupon.setCouponName(bmsDxGroupBuy.getGroupName());
            bmsBusinessCoupon.setCouponContent(JSON.toJSONString(bmsDxGroupBuy));
        }else if(businessCouponReDto.getCouponType() == Constants.BUSINESS_COUPON_CUSTOM){
            Map<String,Object> contentData = JSON.parseObject(bmsBusinessCoupon.getCouponContent());
            bmsBusinessCoupon.setCouponName(contentData.get("name").toString());
            //bmsBusinessCoupon.setCouponContent(contentData.get("content").toString());
        }
        bmsBusinessCoupon.setRemainNum(bmsBusinessCoupon.getSendNum());
        bmsBusinessCouponDao.save(bmsBusinessCoupon);
        Integer nowTimeStamp = DateTimeUtils.converDateToInterger(new Date());
        if(nowTimeStamp >= DateTimeUtils.converDateToInterger(bmsBusinessCoupon.getSendStartTime())){
            bmsBusinessCoupon.setStatus(Constants.COUPON_START);
        }else {
            doBusinessCouponTiming(CouponToSendJob.class,bmsBusinessCoupon.getSendStartTime(),bmsBusinessCoupon);
        }
        if(nowTimeStamp >= DateTimeUtils.converDateToInterger(bmsBusinessCoupon.getSendEndTime())){
            bmsBusinessCoupon.setStatus(Constants.COUPON_STOP);
            bmsBusinessCoupon.setStopStatus(Constants.COUPON_OF_STATUS);
            bmsBusinessCoupon.setStopTime(bmsBusinessCoupon.getSendEndTime());
            bmsBusinessCoupon.setIsOff(Constants.COMMON_FLAG_TRUE_INT);
            bmsBusinessCoupon.setOfflineTime(bmsBusinessCoupon.getSendEndTime());
        }else {
            //设置派发机制（定时触发）
            doBusinessCouponTimingByOff(CouponAsOfJob.class,bmsBusinessCoupon.getSendEndTime(),bmsBusinessCoupon);
        }
        bmsBusinessCouponDao.save(bmsBusinessCoupon);
        Logger logger = BmsCommonService.getLogger(getClass());
        logger.info("SendStartTime : " +  bmsBusinessCoupon.getSendStartTime().toString());
        logger.info("SendEndTime : " +  bmsBusinessCoupon.getSendEndTime().toString());
        logger.info("StartTime : " +  bmsBusinessCoupon.getStartTime().toString());
        logger.info("EndTime : " +  bmsBusinessCoupon.getEndTime().toString());
        setBusinessCoupons(bmsBusinessCoupon);
        return ResultMapHelper.success(bmsBusinessCoupon, ResultMsg.INSERT_SUCCESS);
    }

    public boolean checkDisMax(Date sendStartTime, Date sendEndTime,Integer businessId) {
        final int MAX_DISTRIBUTED = 5;
        Date startTime = DateTimeUtils.getStartTimeOfDay(sendStartTime);
        Date endTime = DateTimeUtils.getStartTimeOfDay(sendEndTime);
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("sendStartTime_LTTE",startTime);
        conditionMap.put("sendEndTime_GTTE",startTime);
        conditionMap.put("businessId",businessId);
        Set<Integer> status = new HashSet<>();
        status.add(Constants.COUPON_STAY_OUT);
        status.add(Constants.COUPON_START);
        conditionMap.put("status_IN",status);
        long firstSize = bmsBusinessCouponDao.count(new SpecificationUtils(conditionMap));
        conditionMap.put("sendStartTime_LTTE",endTime);
        conditionMap.put("sendEndTime_GTTE",endTime);
        conditionMap.put("businessId",businessId);
        long secondSize = bmsBusinessCouponDao.count(new SpecificationUtils(conditionMap));
        return !((firstSize  <= MAX_DISTRIBUTED - 1) && (secondSize <= MAX_DISTRIBUTED - 1));
    }

    /**
     * @Description 定时取消券
     * @Author: cfx
     * @Date: 2019/8/14
     */
    public void doBusinessCouponTiming(Class classes, Date startDate,BmsBusinessCoupon bmsBusinessCoupon){
        Integer bmsBusinessCouponId = bmsBusinessCoupon.getId();
        String jobName = AUTO_SEND_KEY + bmsBusinessCouponId;
        String triggerName = Constants.ORDER_TRI_NAME + bmsBusinessCouponId;
        Map<String,Object> jobDataMap = new HashMap<>();
        jobDataMap.put("couponId",bmsBusinessCoupon.getId());
        QuartzDo.setTask(classes,jobName,triggerName,startDate,jobDataMap);
    }

    @Override
    public Map<String, Object> showCouponList(BusinessCouponReDto businessCouponReDto) {
        Integer status = businessCouponReDto.getStatus();
        Pageable pageable = BmsCommonService.getPageable(businessCouponReDto.getPageNum(),businessCouponReDto.getPageSize(), Sort.Direction.DESC,"newTime");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("businessId",businessCouponReDto.getBusinessId());
        Set<Integer> couponType = new HashSet<>();
        couponType.add(Constants.BUSINESS_COUPON_VOUCHERS);
        couponType.add(Constants.BUSINESS_COUPON_FOOD);
        couponType.add(Constants.BUSINESS_COUPON_GROUP_BUY);
        couponType.add(Constants.BUSINESS_COUPON_CUSTOM);
        conditionMap.put("couponType_IN",couponType);
        if(status == Constants.COUPON_FIND_STATUS_1){
            ;
        }else if(status == Constants.COUPON_FIND_STATUS_2){
            conditionMap.put("status",Constants.COUPON_START);
        }else if(status == Constants.COUPON_FIND_STATUS_3){
            conditionMap.put("status",Constants.COUPON_STAY_OUT);
        }else if(status == Constants.COUPON_FIND_STATUS_4){
            conditionMap.put("status",Constants.COUPON_STOP);
        }
        Page<BmsBusinessCoupon> bmsBusinessCouponPage = bmsBusinessCouponDao.findAll(new SpecificationUtils(conditionMap),pageable);
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("count",bmsBusinessCouponPage.getTotalElements());
        //查询派发中数量
        userDataMap.put("startIngCount",bmsBusinessCouponDao.countCouponStatusNum(businessCouponReDto.getBusinessId(),Constants.COUPON_START));
        userDataMap.put("waitIngCount",bmsBusinessCouponDao.countCouponStatusNum(businessCouponReDto.getBusinessId(),Constants.COUPON_STAY_OUT));
        List<BmsBusinessCoupon> bmsBusinessCoupons = bmsBusinessCouponPage.getContent();
        setBusinessCoupons(bmsBusinessCoupons);
        return ResultMapHelper.success(bmsBusinessCoupons,userDataMap,"OK");
    }

    public void setBusinessCoupons(BmsBusinessCoupon businessCoupon) {
        if(businessCoupon != null ){
            List<BmsBusinessCoupon> businessCoupons = new LinkedList<>();
            businessCoupons.add(businessCoupon);
            setBusinessCoupons(businessCoupons);
        }
    }

    public void setBusinessCoupons(List<BmsBusinessCoupon> bmsBusinessCoupons) {
        if(bmsBusinessCoupons != null && bmsBusinessCoupons.size() > 0){
            for(BmsBusinessCoupon businessCoupon : bmsBusinessCoupons){
                if(businessCoupon.getCouponType() == Constants.BUSINESS_COUPON_GROUP_BUY){
                    Map<String,Object> objectMap = JSON.parseObject(businessCoupon.getCouponContent());
                    BmsDxGroupBuy bmsDxGroupBuy = new BmsDxGroupBuy();
                    BeanUtils.populate(bmsDxGroupBuy,objectMap);
                    List<BmsDxGroupBuy> bmsDxGroupBuys = new ArrayList<>();
                    bmsDxGroupBuys.add(bmsDxGroupBuy);
                    bmsDxGroupBuyService.postHandleGroupContent(bmsDxGroupBuys,true);
                    businessCoupon.setCouponContentDict(JSON.parseObject(JSON.toJSONString(bmsDxGroupBuy)));
                }else {
                    businessCoupon.setCouponContentDict(JSON.parseObject(businessCoupon.getCouponContent()));
                }
                if(businessCoupon.getCouponType() == Constants.BUSINESS_COUPON_MARKET){
                    if(businessCoupon.getCouponContentDict().containsKey("prizeName")){
                        businessCoupon.setCouponName(businessCoupon.getCouponContentDict().get("prizeName").toString());
                    }
                }
            }
        }
    }

    @Override
    public Map<String, Object> showCouponDetail(BusinessCouponReDto businessCouponReDto) {
        Integer id = businessCouponReDto.getId();
        if(businessCouponReDto.getReceCouponId() != null){
            Optional<BmsUserReceCoupon> bmsUserReceCouponOptional = bmsUserReceCouponService.getBaseDao().findById(businessCouponReDto.getReceCouponId());
            if(bmsUserReceCouponOptional.isPresent()){
                id = bmsUserReceCouponOptional.get().getBusinessCouponId();
            }
        }
        Optional<BmsBusinessCoupon> oBusinessCoupon = bmsBusinessCouponDao.findById(id);
        if(!oBusinessCoupon.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_COUPON_NO_EXIST,ResultMsg.CODE_BUSINESS_COUPON_NO_EXIST);
        }
        List<BmsBusinessCoupon> bmsBusinessCoupons = new LinkedList<>();
        bmsBusinessCoupons.add(oBusinessCoupon.get());
        setBusinessCoupons(bmsBusinessCoupons);
        return ResultMapHelper.success(bmsBusinessCoupons.get(0),"OK");
    }

    @Override
    public Map<String, Object> offCoupon(BusinessCouponReDto businessCouponReDto) {
        //Date nowTime = new Date();
        Optional<BmsBusinessCoupon> oBusinessCoupon = bmsBusinessCouponDao.findById(businessCouponReDto.getId());
        if(!oBusinessCoupon.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_COUPON_NO_EXIST,ResultMsg.CODE_BUSINESS_COUPON_NO_EXIST);
        }
        BmsBusinessCoupon bmsBusinessCoupon = oBusinessCoupon.get();
        //BmsBusinessCoupon newBusinessCoupon = new BmsBusinessCoupon();
        //BeanUtils.copyProperties(bmsBusinessCoupon,newBusinessCoupon);
        this.offCouponHand(bmsBusinessCoupon);
        bmsBusinessCouponDao.save(bmsBusinessCoupon);
        //设置克隆券
        /*newBusinessCoupon.setId(null);
        newBusinessCoupon.setIsOff(Constants.COMMON_FLAG_TRUE_INT);
        newBusinessCoupon.setStatus(Constants.COUPON_STOP);
        newBusinessCoupon.setOfflineTime(nowTime);
        newBusinessCoupon.setInGroupGet(Constants.COMMON_FLAG_FALSE_INT);
        newBusinessCoupon.setGroupNoticeGet(Constants.COMMON_FLAG_FALSE_INT);
        newBusinessCoupon.setActivityGet(Constants.COMMON_FLAG_FALSE_INT);
        newBusinessCoupon.setCouponUse(Constants.COMMON_FLAG_FALSE_INT);*/
        bmsBusinessCouponDao.save(bmsBusinessCoupon);
        //bmsBusinessCouponDao.save(newBusinessCoupon);
        return ResultMapHelper.success(bmsBusinessCoupon,ResultMsg.HAND_SUCCESS);
    }

    private void offCouponHand(BmsBusinessCoupon bmsBusinessCoupon) {
        Date nowTime = new Date();
        bmsBusinessCoupon.setIsOff(Constants.COMMON_FLAG_TRUE_INT);
        bmsBusinessCoupon.setStatus(Constants.COUPON_STOP);
        bmsBusinessCoupon.setOfflineTime(nowTime);
        bmsBusinessCoupon.setStopStatus(Constants.COUPON_BUSINESS_OFF);
        bmsBusinessCoupon.setStopTime(nowTime);
    }

    @Override
    public void doBusinessCouponTimingByOff(Class<CouponAsOfJob> couponAsOfJobClass, Date sendEndTime, BmsBusinessCoupon businessCoupon) {
        Integer bmsBusinessCouponId = businessCoupon.getId();
        String jobName = AUTO_OFF_KEY + bmsBusinessCouponId;
        String triggerName = AUTO_OFF_KEY +  bmsBusinessCouponId;
        Map<String,Object> jobDataMap = new HashMap<>();
        jobDataMap.put("couponId",businessCoupon.getId());
        QuartzDo.setTask(couponAsOfJobClass,jobName,triggerName,sendEndTime,jobDataMap);
    }

    @Override
    public Map<String, Object> userGetBusinessCoupon(BusinessCouponReDto businessCouponReDto) {
        Integer businessId = businessCouponReDto.getBusinessId();
        Integer userId = Integer.parseInt(businessCouponReDto.getUserId());
        //获取
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("businessId",businessId);
        conditionMap.put("status",Constants.COUPON_START);
        Set<Integer> couponTypes = new HashSet<>();
        couponTypes.add(Constants.BUSINESS_COUPON_VOUCHERS);
        couponTypes.add(Constants.BUSINESS_COUPON_FOOD);
        couponTypes.add(Constants.BUSINESS_COUPON_GROUP_BUY);
        couponTypes.add(Constants.BUSINESS_COUPON_CUSTOM);
        conditionMap.put("couponType_IN",couponTypes);
        Pageable pageable = BmsCommonService.getPageable(businessCouponReDto.getPageNum(),businessCouponReDto.getPageSize(), Sort.Direction.DESC,"newTime");
        Page<BmsBusinessCoupon> bmsBusinessCouponPage = bmsBusinessCouponDao.findAll(new SpecificationUtils(conditionMap),pageable);
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("count",bmsBusinessCouponPage.getTotalElements());
        List<BmsBusinessCoupon> bmsBusinessCoupons = bmsBusinessCouponPage.getContent();
        setBusinessCoupons(bmsBusinessCoupons);
        setUserRece(userId,bmsBusinessCoupons);
        return ResultMapHelper.success(bmsBusinessCoupons,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    private void setUserRece(Integer userId,List<BmsBusinessCoupon> bmsBusinessCoupons) {
        if(bmsBusinessCoupons != null && bmsBusinessCoupons.size() > 0){
            Set<Integer> businessCuponIds = bmsBusinessCoupons.stream().map(BmsBusinessCoupon::getId).collect(Collectors.toSet());
            Map<Integer,Integer> userReceOverMap = bmsUserReceCouponService.getUserReceOver(userId,businessCuponIds);
            for(BmsBusinessCoupon businessCoupon : bmsBusinessCoupons){
                if(userReceOverMap.containsKey(businessCoupon.getId())){
                    businessCoupon.setUserHavingRece(Constants.COMMON_FLAG_FALSE_INT);
                }
            }
        }
    }

    @Transactional
    public Map<String, Object> userReceiveBusinessCoupon(ParamsMap paramsMap) {
        Integer receChannel = paramsMap.getInteger("receChannel");
        Integer businessCouponId = paramsMap.getInteger("businessCouponId");
        Integer userId = paramsMap.getInteger("userIdentify");
        BmsBusinessCoupon businessCoupon = bmsBusinessCouponDao.findByIdAndIsDelete(businessCouponId,Constants.COMMON_FLAG_FALSE_INT);
        if(businessCoupon == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_COUPON_NO_EXIST,ResultMsg.CODE_BUSINESS_COUPON_NO_EXIST);
        }
        if(businessCoupon.getStatus() != Constants.COUPON_START){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_COUPON_STOP_DIS,ResultMsg.CODE_BUSINESS_COUPON_STOP_DIS);
        }
        //判断用户领取是否达到限制数量
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("type",Constants.BUSINESS_PRODUCE);
        conditionMap.put("businessCouponId",businessCouponId);
        List<BmsUserReceCoupon> bmsUserReceCoupons = bmsUserReceCouponService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
        if(businessCoupon.getLimitOnceUse() != null) {
            int limitReceNum = businessCoupon.getLimitOnceUse();
            if (bmsUserReceCoupons != null && bmsUserReceCoupons.size() >= limitReceNum) {
                return ResultMapHelper.result(ResultCode.CODE_USER_RECE_MAX, ResultMsg.CODE_USER_RECE_MAX);
            }
        }
        //查看券是否派完
        if(businessCoupon.getRemainNum() <= 0){
            //同时下线该券
            this.offCouponHand(businessCoupon);
            businessCoupon.setStopStatus(Constants.ALL_COUPON_STATUS);
            bmsBusinessCouponService.getBaseDao().save(businessCoupon);
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_COUPON_SEND_OUT,ResultMsg.CODE_BUSINESS_COUPON_SEND_OUT);
        }
        //领券
        businessCoupon.setRemainNum(businessCoupon.getRemainNum() - 1);
        if(receChannel == Constants.GROUP_IN_GET){
            businessCoupon.setInGroupGet(businessCoupon.getInGroupGet() == null ? 1 : (businessCoupon.getInGroupGet() + 1));
        }else if(receChannel == Constants.GROUP_ANNOUN_GET){
            businessCoupon.setGroupNoticeGet(businessCoupon.getGroupNoticeGet() == null ? 1 : (businessCoupon.getGroupNoticeGet() + 1));
        }
        //插入领券对象
        BmsUserReceCoupon receCoupon = new BmsUserReceCoupon();
        receCoupon.setType(Constants.BUSINESS_PRODUCE);
        receCoupon.setUserId(userId);
        receCoupon.setBusinessId(businessCoupon.getBusinessId());
        receCoupon.setBusinessCouponId(businessCouponId);
        receCoupon.setStatus(Constants.COMMON_FLAG_FALSE_INT);
        receCoupon.setExpireTime(businessCoupon.getEndTime());
        receCoupon.setNewTime(new Date());
        if(businessCoupon.getCouponType() == Constants.BUSINESS_COUPON_FOOD
                || businessCoupon.getCouponType() == Constants.BUSINESS_COUPON_GROUP_BUY
                || businessCoupon.getCouponType() == Constants.BUSINESS_COUPON_CUSTOM
                || businessCoupon.getCouponType() == Constants.BUSINESS_COUPON_MARKET){
            receCoupon.setConsumerCode(OrderUtils.getGroupBuyPayNo(false));
        }
        bmsUserReceCouponService.getBaseDao().save(receCoupon);
        bmsBusinessCouponDao.save(businessCoupon);
        List<BmsBusinessCoupon> bmsBusinessCoupons = new ArrayList<>();
        bmsBusinessCoupons.add(businessCoupon);
        setBusinessCoupons(bmsBusinessCoupons);
        setUserRece(userId,bmsBusinessCoupons);
        handleBusinessCouponsOff(bmsBusinessCoupons);
        List<BmsUserReceCoupon> receCoupons = new ArrayList<>();
        receCoupons.add(receCoupon);
        bmsVerRecordService.addRecordByReceQuan(receCoupons);

        return ResultMapHelper.success(bmsBusinessCoupons.get(0),ResultMsg.MSG_GET_SUCCESS);
    }

    private void handleBusinessCouponsOff(List<BmsBusinessCoupon> bmsBusinessCoupons) {
        if(bmsBusinessCoupons != null && bmsBusinessCoupons.size() > 0){
            for(BmsBusinessCoupon bmsBusinessCoupon : bmsBusinessCoupons){
                if(bmsBusinessCoupon.getRemainNum() <= 0){
                    //同时下线该券
                    this.offCouponHand(bmsBusinessCoupon);
                    bmsBusinessCoupon.setStopStatus(Constants.ALL_COUPON_STATUS);
                    bmsBusinessCouponService.getBaseDao().save(bmsBusinessCoupon);
                }
            }
        }
    }

    @Override
    public Map<Integer, BmsBusinessCoupon> getBusinessCoupon(Set<Integer> couponIds) {
        Map<Integer, BmsBusinessCoupon> bmsBusinessCouponMap = new HashMap<>();
        List<BmsBusinessCoupon> bmsBusinessCoupons = bmsBusinessCouponDao.findByIdIn(couponIds);
        if(bmsBusinessCoupons != null && bmsBusinessCoupons.size() > 0){
            for(BmsBusinessCoupon businessCoupon : bmsBusinessCoupons){
                bmsBusinessCouponMap.put(businessCoupon.getId(),businessCoupon);
            }
        }
        return bmsBusinessCouponMap;
    }
}
